#include <bits/stdc++.h>
using namespace std;
#define int long long

void solve() {
    int n;
    cin >> n;
    vector<int> a(n + 1), c(n + 1), cnt(n + 1);
    for(int i = 1; i <= n; i++) cin >> a[i], cnt[a[i]]++;
    for(int i = 1; i <= n; i++) cin >> c[i];
    vector<int> ans;
    vector<bool> st(n + 1);
    queue<int> q;
    for(int i = 1; i <= n; i++) {
        if(cnt[i] == 0){
            q.push(i);
            ans.push_back(i);
            st[i] = true;
        }
    }
    while(q.size()) {
        auto t = q.front();
        q.pop();
        if(--cnt[a[t]] == 0) st[a[t]] = true, q.push(a[t]), ans.push_back(a[t]);
    }
    for(int i = 1; i <= n; i++) {
        if(!st[i]) {
            int mi = c[i];
            int id = i;
            auto dfs = [&](auto&& dfs, int u)->void {
                if(st[u]) return;
                st[u] = true;
                int x = a[u];
                if(c[x] < mi) {
                    mi = c[x];
                    id = x;
                }
                dfs(dfs, x);
            };
            dfs(dfs, i);
            int x = a[id];
            do{ 
                ans.push_back(x);
                x = a[x];
            }while(a[id] != x);
        }
    }
    for(auto x : ans) cout << x << ' ';
    cout << '\n';

}

signed main() {
    int t; cin >> t;
    while(t--) solve();
    return 0;
}